package com.firmboy.thread.callable;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 测试callable和future框架
 *
 * @author firmboy
 * @create 2018-05-17 下午6:09
 **/
public class CallableAndFuture {

    @Test
    public void callable(){
        Callable<Integer> callable = new Callable<Integer>(){

            @Override
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };

        FutureTask<Integer> future = new FutureTask<Integer>(callable);

        new Thread(future).start();
        try{
            Thread.sleep(5000);
            System.out.println(future.get());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void callableand(){
        ExecutorService service = Executors.newSingleThreadExecutor();

        Future<Integer> future = service.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Thread.sleep(10000);
                return new Random().nextInt(100);
            }
        });

        try{
            long start = System.currentTimeMillis();
            System.out.println(future.get());
            long end = System.currentTimeMillis();
            System.out.println("耗时："+(end-start));
        }catch(Exception e){
            e.printStackTrace();
        }


    }
}
